package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.pojo.JsonResult;
import com.example.demo.pojo.User;
import com.example.demo.pojo.security.UserSecurity;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;

@RestController
public class UserController {
    @Resource
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private BCryptPasswordEncoder bcryptPasswordEncoder;
    @PostMapping("/loginUser")
    public JsonResult  login(@RequestBody User user,HttpServletResponse http)  {
        String enUpdatePassword = bcryptPasswordEncoder.encode("123456");
        System.out.println(enUpdatePassword);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getName(), user.getPas());
        //  得到 AuthenticationManager 这个管理器，是一个接口
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        UserSecurity principal = (UserSecurity) authentication.getPrincipal();
        String uuid = principal.getUser().getId().toString();
        redisUtil.set(uuid, principal);
        //
        System.out.println("userSecurity = " +principal.getUser().toString());
        System.out.println(authentication.toString());
        //拿到登录用户
        //设置响应头
        http.setHeader("Access-Control-Expose-Headers", "Authorization");
        String token = JwtUtil.createToken(uuid);
        //返回给前端
        http.setHeader("Authorization", token);
        return new JsonResult(token);
    }
    @PostMapping("/save")
    public JsonResult  save(@RequestBody User user) throws Exception {
        String enUpdatePassword = bcryptPasswordEncoder.encode(user.getPas());
        user.setPas(enUpdatePassword );
        boolean save = userService.save(user);
        return new JsonResult();
    }
}
